//
// Created by Apple on 2021/5/30.
//

#ifndef TIMER_H
#define TIMER_H

#include <unordered_map>
#include "Random.hpp"
#include "TimerInternal.hpp"

namespace TWT {
namespace Util {


class Timer {
public:
    Timer();
    ~Timer();
    template<typename WatiHhander>
    static void runOnce(const WatiHhander& hander, int waitTimer){
        auto timer = std::make_shared<TimerInternal>(NetWork::NetContext::instance());
        timer->runOnce(hander,waitTimer);
    }

    template<typename WatiHhander>
    static uint32_t runEvery(const WatiHhander& hander, int timeInterval){
        auto timer = std::make_shared<TimerInternal>(NetWork::NetContext::instance());
        timer->runEvery(hander,timeInterval);
        int value = Random::rand();
        timers_[value] = timer;
        return value;
    }

    static void cancel(uint32_t timerId){
        auto iter = timers_.find(timerId);
        if(iter != timers_.end()){
            auto timer = iter->second.lock();
            if(timer != nullptr){
                timer->cancel();
            }
        }
    }

    static Timer& instance(){
        static Timer instance_;
        return instance_;
    }


private:
    static std::unordered_map<uint32_t, std::weak_ptr<TimerInternal>> timers_;
};

std::unordered_map<uint32_t, std::weak_ptr<TimerInternal>> Timer::timers_;
}
}

#endif //TIMER_H
